package study.feign;

import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import study.vo.User;

/**
 * 如果直接实现MyFeignClient，那么无法获取到异常信息，所以要这么处理
 */
@Component
public class MyFeignClientFallback implements FallbackFactory<MyFeignClient>{
    Logger logger = LoggerFactory.getLogger(MyFeignClientFallback.class);
    @Override
    public MyFeignClient create(Throwable ex) {

        return new MyFeignClient(){

            @Override
            public String hello() {
                String msg = "";
                if (ex instanceof FlowException) {
                    msg = "限流了";
                } else if (ex instanceof DegradeException) {
                    msg = "降级了";
                } else if (ex instanceof ParamFlowException) {
                    msg = "热点参数限流";
                } else if (ex instanceof SystemBlockException) {
                    msg = "系统规则（负载/...不满足要求）";
                } else if (ex instanceof AuthorityException) {
                    msg = "授权规则不通过";
                }else{
                    msg = ex.getMessage();
                }

                logger.error(MyFeignClient.class.getSimpleName()+"#hello服务出现异常："+msg,ex);
                return "hello的降级服务！！！("+msg+")";
            }

            @Override
            public String updateUser3(String userName, String password) {
                return "updateUser3的降级服务！！！1";
            }

            @Override
            public String updateUser2(User user) {
                return "updateUser2的降级服务！！！1";
            }
        };
    }
}
